package com.hmall.search.listener;

import com.hmall.api.client.ItemClient;
import com.hmall.api.dto.OrderDetailDTO;
import com.hmall.search.service.SyncItemDataToES;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

/**
 * 商品数据变更监听器-监听MQ中的消息，同步数据到ES中
 *
 * @author xiaopeng
 * @version 1.0
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ItemChangeListener {

    private final SyncItemDataToES syncItemDataToES;

    // 处理商品新增/更新
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "search.item.insert_update.queue"),
            exchange = @Exchange(name = "search.direct", type = ExchangeTypes.DIRECT),
            key = "item.save_update"
    ))
    public void listenItemInsertOrUpdate(Long id) throws IOException {
        // 实际项目中这里应该调用item-service的feign客户端获取最新商品数据
        syncItemDataToES.insertOrUpdateById(id);
    }

    // 处理商品删除
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "search.item.delete.queue"),
            exchange = @Exchange(name = "search.direct", type = ExchangeTypes.DIRECT),
            key = "item.delete"
    ))
    public void listenItemDelete(Long id) throws IOException {
        syncItemDataToES.deleteById(id);
    }

    // 更新商品库存： 批量扣减库存,批量恢复库存
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "search.item.deductStock.queue"),
            exchange = @Exchange(name = "search.direct", type = ExchangeTypes.DIRECT),
            key = "item.updateStock"
    ))
    public void listenStockChange(List<Long> ids) throws IOException {
        syncItemDataToES.updateStock(ids);
    }


}
